import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAContext';
import { Form, Select, Spin, Tooltip, TreeSelect, message, Button } from 'antd';
import { useDescriptions, Descriptions } from '@/components/Descriptions';
import pageStyles from '@/common/pageLayout.less';
import { downloadTemplate, getFileNameNotType, getLoadMapList, getTenantID, splitFileUrl } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import MyIcon from '@/components/MyIcon';
import { formatDecimal } from '../../Acommon';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { RegularExpression } from '@/common/constVariable';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import DetailInfoTableList from './DetailInfoTableList';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';
import moment from 'moment';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 引入上下文 */
  const { styleFixCls, infoObj } = useContext(ChangeControllerContext);

  const [isPass, setIsPass] = useState<boolean>(false); // 是否通过线下审批

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //资产来源
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //资产品牌
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
  ]);

  const [changeFromRef] = Form.useForm(); // 表单实例

  // 内部还是跨部门
  const [isIntoDep, setIsIntoDep] = useState<boolean>(true);

  /** 获取组织机构树接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /** 获取当前部门用户数据 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {
    /** 初始化请求组织机构 */
    let payload = {
      params: '0',
      flowType: '0',
    };
    getFlowOrgTreeRun(payload);
    if (infoObj?.id) {
      setIsIntoDep(infoObj.allotType == 1);

      getUserRun({
        //获取当前部门用户信息
        userDepartmentID: infoObj?.useDepartmentID,
      });
      BasicMethods?.setFieldsValue({
        ...infoObj,
        createTime: moment(infoObj?.createTime).format('YYYY-MM-DD'),
        expectSum: formatDecimal(infoObj?.expectSum),
      });
      ReMethods?.setFieldsValue({
        ...infoObj,
        createTime: moment(infoObj?.createTime).format('YYYY-MM-DD'),
        expectSum: formatDecimal(infoObj?.expectSum),
      });
    }
  }, [infoObj]);

  // 表格表单配置信息
  const [config, BasicMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        field: `createTime`,
        label: `申请日期`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
      },
      {
        field: `applyCode`,
        label: `流水单号`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
      },
      {
        field: `createrName`,
        label: `申请人`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `createPhone`,
        label: `联系电话`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `createDepartmentName`,
        label: `申请部门/单位`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `createPositionName`,
        label: `职务岗位`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
    ],
  });

  // 表格表单配置信息
  const [ReConfig, ReMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        field: `applyTitle`,
        label: `事项名称`,
        component: 'Input',
        disabled: true,
        colSpan: 0,
        placeholder: '自动带出',
      },
      {
        field: `allotType`,
        label: `交接类型`,
        component: 'Render',
        disabled: true,
        placeholder: '自动带出',
        render: () => {
          return <span>{infoObj.allotType ? (infoObj.allotType === 1 ? '部门内部' : infoObj.allotType === 2 ? '跨部门' : '--') : '--'}</span>;
        },
      },
      {
        field: `originalDepartmentName`,
        label: `移交使用部门`,
        component: 'Render',
        disabled: true,
        ishidden: isIntoDep,
        placeholder: '自动带出',
        render: () => {
          return <span>{infoObj.originalDepartmentName ? infoObj.originalDepartmentName : '--'}</span>;
        },
      },
      {
        field: `newDepartmentName`,
        label: `接收使用部门`,
        component: 'Render',
        disabled: true,
        ishidden: isIntoDep,
        placeholder: '自动带出',
        render: () => {
          return <span>{infoObj.newDepartmentName ? infoObj.newDepartmentName : '--'}</span>;
        },
      },
      {
        field: `newerName`,
        label: `接收使用人`,
        component: 'Render',
        disabled: true,
        // colSpan: 2,
        placeholder: '自动带出',
        render: () => {
          return <span>{infoObj.newerName ? infoObj.newerName : '--'}</span>;
        },
      },
      {
        field: `applyInfo`,
        label: `申请理由`,
        component: 'InputTextArea',
        disabled: true,
        placeholder: '自动带出',
        required: false,
        // colSpan: 2,
        allowClear: true,
        showCount: true,
        maxLength: 500,
        autoSize: { minRows: 2, maxRows: 4 },
      },
      {
        field: `applyFile`,
        label: `相关附件`,
        component: 'Render',
        placeholder: '请上传',
        render: (text, record) => {
          const fileName = 'applyFile';
          return (
            <div
              style={{
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                marginLeft: '8px',
              }}
            >
              {record?.[fileName]
                ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                    return (
                      <div>
                        <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                          <a
                            onClick={() => {
                              message.success('下载中，请稍后...');
                              downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                            }}
                          >
                            <MyIcon type="icon-file-text-fill" />
                            &nbsp;
                            {getFileNameNotType(e.attachName, 8)}
                          </a>
                        </Tooltip>
                        {/* 轻阅读预览 */}
                        <Tooltip title={'在线预览'}>
                          <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                        </Tooltip>
                      </div>
                    );
                  })
                : '--'}
            </div>
          );
        },
      },
    ],
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '20px 10%' }}>
            <Spin spinning={mapLoading}>
              <TypographyTitle children={'资产交接申请'} style={{ textAlign: 'center', borderLeft: 'none' }} level={1} />
              <TypographyTitle children={'基本信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={config} />

              <TypographyTitle children={'资产交接信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={ReConfig} />

              {/* 列表数据 */}
              <TypographyTitle children={'资产详单'} style={{ margin: '25px 0px 20px' }} level={2} />
              <DetailInfoTableList dataList={infoObj?.massetApplyNumberList || []} mapLoading={mapLoading} loadMapInfo={loadMapInfo} />
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};
